<?php
use think\facade\Db;

// 应用公共文件

/**
 * unicode翻转
 * @param string $str
 * @return mixed
 */
function decode_unicode($str)
{
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}

/**
 * 判断是否为邮箱
 * @param unknown_type $email
 * @return boolean true: 是邮箱, false: 不是邮箱
 */
function is_email($email)
{
    $filter  = "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
    return preg_match($filter, $email);
}

/**
 * 去掉两端空白字符和&nbsp;
 * @param strObj
 * @returns
 */
function replace_blank($str)
{
    return trim(str_replace('&nbsp;', '', trim($str)));
}

/**
 * 判断是否为http开头 是返回原link 不是拼装http://
 * @param  $link
 * @return string
 */
function check_http_start($link)
{
    $pattern = '/^http[s]?:\/\/.+$/';
    $link    = trim($link);

    if (preg_match($pattern, $link)) {
        return $link;
    }

    return 'http://'.$link;
}

/**
 * 验证
 * @param int $response_type
 * @param string $response_content
 * @return mixed
 */
function customer_content_filter($content)
{
    $content = html_entity_decode($content);

    // 回复的内容
    $content  = trim(strip_tags($content, '<img><div><br><a>'));

    if (replace_blank($content) == "") {
        return '';
    }
    $content = str_replace('</div>', '', str_replace('<div>', '<br>', $content));
    $content = preg_replace('/\<br.*?\>/', '<br>', $content);
    $content = str_replace(array('IMG', 'HREF', 'SRC', '<A', '</A>'), array('img', 'href', 'src', '<a', '</a>'), $content);

    if (!$content) {
        return '';
    }

    $tmp_content = str_replace(' ', '', strip_tags($content, '<img><a>'));
    if (!$tmp_content) {
        return '';
    }

    return $content;
}


/**
 * 随机产生A-Z, a-z, 0-9的字符串
 * @param int $length 随机数的长度
 * @return string
 */
function random_hash($length = 10)
{
    $salt = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
    $count = count($salt);
    $hash = '';
    for ($i = 0; $i < $length; $i++) {
        $hash .= $salt[mt_rand(0, $count-1)];
    }
    return $hash;
}

/**
 * 是否在微信浏览器中
 * @return boolean
 */
function is_weixin()
{
    if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }

    return false;
}

// 查询一条资源信息
function _uri($res, $filter = [], $field = '', $order = [])
{
    if (!$filter) {
        return [];
    }

    if ($field) {
        if (!$order) {
            $order = ['id', 'desc'];
        }
        return Db::table($res)->field($field)->where($filter)->order($order[0], $order[1])->find();
    }

    if ($order) {
        if (!$order) {
            $order = ['id', 'desc'];
        }
        return Db::table($res)->where($filter)->order($order[0], $order[1])->find();
    }

    return Db::table($res)->where($filter)->find();
}

function _model($res, $filter, $method) {
    return Db::table($res)->where($filter)->$method();
}

function getFields($res, $field='*', $filter=['status'=>1], $order = ['id', 'desc'], $limit = 0)
{
    if ($field == '*') {
        return [];
    }

    if ($limit) {
        $res = Db::table($res)->field($field)->where($filter)->order($order[0], $order[1])->limit($limit)->select()->toArray();
    } else {
        $res = Db::table($res)->field($field)->where($filter)->order($order[0], $order[1])->select()->toArray();
    }

    $new_list = [];
    foreach ($res as $k => $v) {
        $new_list[$k] = $v[$field];
    }

    return $new_list;
}

function _return($msg)
{
    return \view('common@admin/msg',['msg'=>$msg]);
}

/**
 * 时间格式化
 * @param int $time
 * @param string $format
 * @return string
 */
function time_format($time, $format = "Y-m-d H:i")
{
    $tmp_time = strtotime($time);
    if ($tmp_time < strtotime('2038-12-31')) {
        return date($format, $tmp_time);
    } else {
        return date_format(date_create($time), $format);
    }

}

/*
 * 根据给定的资源名和资源id获取它的title，当获取到时，返回title，没有获取则返回FALSE
 * @param $res_name
 * @param $res_id
 */
function display_title($res_name, $res_id, $title = 'title')
{
    if (empty($res_id) || empty($res_name)) {
        return '';
    }

    $res_title = _uri($res_name, ['id' => $res_id], $title);

    return $res_title[$title];
}

function filter_string($string, $quote_style = ENT_QUOTES)
{
    return htmlspecialchars($string, $quote_style);
}

/**
 * 更改某资源的相关字段
 * @param string $res_name
 * @param int $res_id
 * @param array $info
 * @return boolean
 */
function update_res_field($res_name, $res_id, $info, $auto = 0 )
{
    if (empty($res_id) || empty($res_name)) {
        return FALSE;
    }

    $res_info = _uri($res_name, ['id'=>$res_id]);
    if (empty($res_info)) {
        return FALSE;
    }

    if (is_array($info)) {
        foreach ($info as $k=>$v) {
            if (!array_key_exists($k, $res_info)) {
                return FALSE;
            }

            if (!is_numeric($v)) {
                $info[$k] = filter_string($v);
            }
        }

        return Db::name($res_name)->where(['id'=>$res_id])->data($info)->update();
    }

    if ($auto) {
        return Db::table($res_name)->where('id', $res_id)->inc($info)->update();
    }
}

/**
 * 获取指定路径图片的缩略图
 * @param string $path 图片路径
 * @param string $prefix 缩略图前缀名称：''-原始图片（默认）；small-小图； middle-中图；big-大图……
 * @param string @res_name 图片所属资源（用来显示指定资源的默认图）
 * @return string 图片的完整路径
 * @author gaojj@alltosun.com
 */
function _image($path, $prefix = '', $res_name = '', $is_all_path = 0)
{
    if (strpos($path, 'http:/') !== false) {
        return $path;
    }

    $default_url = SITE_URL.'/static/images/m/default/article_default.jpg';

    // @FIXME general.gif默认图片，如果视频、文章等默认图片不同的话则存在问题
    if (!$path) {
        if (!$res_name) {
            return $default_url;
        }

        if ($res_name == 'user') {
            $file_path = SITE_URL.'/static/images/default/avatar.jpg';
            return $file_path;
        }
    }

    $path_info = pathinfo($path);
    $file_path = '';

    // 如果是gif，显示原图
    //an_dump($path_info);
    if ($path_info && strtolower($path_info['extension']) == 'gif') {
        $file_path = $path;
    } else {
        if (!empty($prefix)) {
            $file_path = $path_info['dirname'].'/'.$prefix.'_'.$path_info['basename'];
        } else {
            $file_path = $path;
        }
    }

    //如果传入的路径没有标明上传文件夹的话，则补全路径
    if (substr($file_path, 0, strlen(UPLOAD_FOLDER)) != UPLOAD_FOLDER) {
        $file_path = UPLOAD_FOLDER.'/'.ltrim($file_path, '/');
    }

    // if (!file_exists(ROOT_PATH.'/'.$file_path)) return '/static/images/default/general.gif';

    if (!file_exists(UPLOAD_DIR.'/'.$file_path)) return '';

    if ($is_all_path == 1 && strpos($file_path, SITE_URL) === false) {
        return SITE_URL.'/'.$file_path;
    } else {
        return '/'.$file_path;
    }
}

/**
 * 获取文件的附件类型（用于`attachment`.`type`）
 * @param $file_path 文件路径
 * @return int 附件类型（1-图片；2-视频）
 * @author gaojj@alltosun.com
 */
function get_attachment_type($file_path)
{
    $path_info = pathinfo($file_path);
    $attachment_type = 0;
    if (in_array($path_info['extension'], \think\facade\Config::get('admin.allow_image_type'))) $attachment_type = 1;
    if (in_array($path_info['extension'], \think\facade\Config::get('admin.allow_flash_type'))) $attachment_type = 2;
    return $attachment_type;
}

/**
 * 组装存储文件名
 * @param unknown $file
 * @param unknown $ext
 * @return string
 */
function build_target_name($ext, $target_dir = '', $target_file_name = '')
{
    $time = time();
    $path = date('/Y/m/d', $time);
    //$folder = UPLOAD_PATH.'/2014/03/31';
    $folder = UPLOAD_PATH;

    if ($target_dir) {
        $folder .= '/'.$target_dir;
        if (!file_exists($folder)) {
            @mkdir($folder, 0777, true);
        }
    }

    // 如果传递了图片名字，直接显示图片名
    if ($target_file_name) {
        $target = $folder.'/'.$target_file_name.'.'.$ext;

        return $target;
    }

    $tmp_arr = explode('/', ltrim($path, '/'));
    foreach($tmp_arr as $k=>$v) {
        $folder .= '/'.$v;

        if (!file_exists($folder)) {
            @mkdir($folder, 0777, true);
        }
    }

    //var_dump($tmp_arr, $folder);
    //exit;

    static $count = 1;
    // u为microseconds，> PHP 5.2.2
    if (version_compare(PHP_VERSION, '5.2.2') >= 0) {
        $current_time = date('YmdHisu', $time);
    } else {
        $current_time = date('YmdHis', $time);
    }

    $random = mt_rand(0, 100);

    $target = $folder.'/'.$current_time.'_'.$count.'_'.'_'.$random.'.'.$ext;

    $target = trim($target, '.');
    $count++;

    return $target;
}


/**
 * size的换算
 * @param $number
 * @return string
 */
function conversion($number)
{
    $num = strlen($number);
    if ($num > 9) {
        $num = $num - 9;
        return substr($number, 0, $num)."GB";
    } elseif ($num > 6) {
        $num = $num - 6;
        return substr($number, 0, $num)."MB";
    } elseif ($num > 3) {
        $num = $num -3;
        return substr($number, 0, $num)."KB";
    } else {
        return $number."B";
    }
}

/**
 * 检查链接
 * @param string $content
 * @return boolean
 */
function has_out_link($content)
{
    $img = array();

    preg_match_all('\'<img[^>]*?>\'', $content, $img);

    // 如果没有图片信息 直接返回原内容
    if (!isset($img[0]) || !$img[0]) {
        return false;
    }

    //var_dump($img);exit;

    // 如果存在图片，取出图片内容，进行上传
    $pattern ='<img.*?src="(.*?)".*?>';

    foreach ($img[0] as $k=>$v) {
        $html = $v;
        preg_match($pattern, $html, $matches);

        if ($matches[1]) {
            $per_img_src = $matches[1];
            //if (strpos($per_img_src, SITE_URL) === false && strpos($per_img_src, '/static/upload') === false) {
            if (strpos($per_img_src, SITE_URL) === false && strpos($per_img_src, '/storage/upload') === false) {
                return true;
            }

            // 含有.bmp文件，这个微信上传接口不支持
            if (strpos($per_img_src, '.bmp') !== false) {
                return true;
            }
        }
    }

    return false;
}

/**
 * 获取图片的信息
 * @param string $name 图片名字(带路径)
 * @author qianym@alltosun.com
 */
function get_image_info($filename) {
    // 或该图不存在，则直接返加为空
    if (!file_exists($filename)) {
        return array();
    }

    $data    = getimagesize($filename);
    $imgInfo["width"]  = $data[0];
    $imgInfo["height"] = $data[1];
    $imgInfo["type"]   = $data[2];

    return $imgInfo;
}


/**
 * 验证文件上传状态
 * @param array $file_info 上传的文件信息，$_FILES['name']
 * @param int $max_size 图片大小
 * @param $type 类型 0:图片; 1:附件
 * @return string 错误信息failed_msg
 * @author gaojj@alltosun.com
 */
function check_upload($file_info = NULL, $max_size = 0, $type = 0)
{
    if (!isset($file_info)) {
        return '没有找到上传的文件';
    }
    if (isset($file_info['error']) && $file_info['error'] != 0) {
        $error_mapping = array(
            0   =>  "上传成功！",
            1   =>  "服务器限制的上传文件大小为".ini_get('upload_max_filesize'),
            2   =>  "上传文件大小超过了表单中MAX_FILE_SIZE的限制！",
            3   =>  "只有部分文件被上传了，请重试！",
            4   =>  "没有选择要上传的文件。",
            6   =>  "服务器上传临时目录不存在，请联系系统管理员。",
            7   =>  "文件无法写入磁盘，请联系系统管理员。",
            8   =>  "某个PHP扩展导致上传失败，请联系系统管理员。"
        );

        $error_id = $file_info['error'];

        return '上传失败，'.$error_mapping[$error_id];
    }

    if (empty($file_info['size'])) {
        return '选中的文件大小为空';
    }

    if ($type == 1) {
        $allow_max_size = $max_size ? $max_size : config('admin.attachment_max_size');
        $allow_type = config('admin.allow_type');
    } else {
        $allow_max_size = $max_size ? $max_size : config('admin.image_max_size');
        $allow_type =config('admin.allow_image_type');
    }

    $file_extension_name = pathinfo($file_info['name'], PATHINFO_EXTENSION);
    if (!in_array(strtolower($file_extension_name), $allow_type)) {
        $name = json_encode($file_info['name']);
        //$ext = json_encode($file_extension_name);
        //$all_type = json_encode($allow_type);

        return '上传文件的类型不允许';
    }

    if ($allow_max_size && $file_info['size'] > $allow_max_size) {
        return '上传文件的大小不得超过'.conversion($allow_max_size);
    }

    if (empty($file_info['name'])) {
        return '选中的文件没有文件名';
    }

    if (empty($file_info['tmp_name'])) {
        return '上传到服务器临时目录失败';
    }

    return '';
}

function getList($res, $filter, $order = ['id', 'desc'], $is_page = 1 , $limit = 0)
{
    //执行查询
    if ($is_page) {
        $list = Db::name($res)->where($filter)->order($order[0], $order[1])->paginate(config('admin.per_page'))->toArray();
    } else if ($limit) {
        $list = Db::name($res)->where($filter)->order($order[0], $order[1])->limit($limit)->select()->toArray();
    } else {
        $list = Db::name($res)->where($filter)->order($order[0], $order[1])->select()->toArray();
    }

    if ($is_page && empty($list['data'])) {
        return [];
    }

    if (!$is_page &&empty($list)) {
        return [];
    }

    return $list;
}

function getTotal($res, $filter = [], $field = 'id')
{
    if ($filter) {
        return Db::table($res)->where($filter)->count($field);
    }

    return Db::table($res)->count($field);
}

/**
 * curl
 * @param str $url
 * @param string $data
 * @return mixed
 */
function h_curl($url, $data = null, $deep_decode = 0, $is_json = 1)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        if (is_array($data)) {
            //$data = http_build_query($data);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);

    //an_dump($output);

    if ($is_json == 1) {
        if ($deep_decode) {
            return json_decode($output, true);
        } else {
            return json_decode($output);
        }
    }

    return $output;
}

/**
 * curl操作
 */
function curl($url, $type = "GET", $data = '')
{
    $header = array(
        'Accept:application/json, text/javascript, */*; q=0.01',
        'Accept-Charset:UTF-8,*;q=0.5',
        //'Accept-Encoding:gzip,deflate,sdch',
        'Accept-Language:zh-CN,zh;q=0.8',
        'Cache-Control:no-cache',
        'Connection:keep-alive',
        'Content-Type:application/x-www-form-urlencoded; charset=UTF-8',
        'Host:mp.weixin.qq.com',
        'Origin:https://mp.weixin.qq.com',
        'Pragma:no-cache',
        //'Referer:https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm-login&lang=zh_CN',
        'Referer:https://mp.weixin.qq.com/',
        'X-Requested-With:XMLHttpRequest',
    );
    $ch = curl_init();
    $option = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => 0,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17",
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_MAXREDIRS => 4,
        CURLOPT_RETURNTRANSFER => TRUE,
        //CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
        CURLOPT_SSL_VERIFYPEER => FALSE
        //CURLOPT_SSL_VERIFYHOST =>
    );

    if ( $type == 'POST' ) {
        $option[CURLOPT_POST] = 1;
    }
    if ( $data ) {
        $option[CURLOPT_POST] = 1;
        $option[CURLOPT_POSTFIELDS] = $data;
    }

    curl_setopt_array($ch, $option);
    $response = json_decode(curl_exec($ch));

    $curl_no  = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    return $response;
}

/**
 * 得到res_type对应的所有信息 类名，表名(后补res_type)
 * 使用内存缓存，memcache共2级缓存
 * @param $res_type 可以为res_type或res_name
 * @param $field 为字段名
 * @return array('id'=>'6', 'name'=>'product', 'model'=>'product', 'table'=>'product')
 */
function get_resource($res_type, $field=null)
{
    if ($res_type) return false;
    else return _uri('resource', $res_type, $field);
}


/**
 * 从配置文件读取缩略图配置
 * @param mixed $res_type
 * @param $category_id 对应分类id
 * @return array
 */
function get_res_thumb($res_name, $category_id = 0)
{
    $res_thumb = config('admin.res_thumb');

    $res_type = $res_name;
    if (is_numeric($res_type)) {
        $res_name = get_resource($res_type, 'name');
    }

    $thumb_set = isset($res_thumb[$res_name]) ? $res_thumb[$res_name] : array();

    // 支持资源的不同分类生成不同的缩略图
    if (isset($thumb_set['category'])) {
        // 如果传入category_id，则采用对应分类的缩略图设置
        if (!empty($category_id) && isset($thumb_set['category'][$category_id])) {
            return $thumb_set['category'][$category_id];
        }
        // 未定义该分类的缩略图设置，或者未传入category_id，则采用默认的缩略图设置
        return $thumb_set['category'][0];
    }

    return $thumb_set;
}


/**
 * 生成缩略图
 * @param $file_path 原图路径
 * @param $res_type 资源类型
 * @param $category_id 对应分类id
 * @return bool
 */
function make_thumb($file_path, $res_name, $category_id = 0, $prefix='')
{
    if (empty($res_name) || empty($file_path)) return false;
    // 从配置文件读取缩略图配置
    $thumb_set = get_res_thumb($res_name, $category_id);

    if (empty($thumb_set)) return false;

    $file_path = UPLOAD_PATH.$file_path;
    $path_info = pathinfo($file_path);

    // 缩略图模式，默认为切图
    $thumb_mode = 'cut';
    if (isset($thumb_set['mode'])) {
        $thumb_mode = $thumb_set['mode'];
        unset($thumb_set['mode']);
    }
    // 生成缩略图
    foreach ($thumb_set as $k=>$v) {
        if (!empty($prefix) && $k != $prefix) {
            continue;
        }
        // 缩略图路径
        $thumb_path = $path_info['dirname'].'/'.$k.'_'.$path_info['basename'];

        $new_width  = $v[0];
        $new_height = $v[1];
        // 按照最大宽度/最大高度进行等比缩放
        if ($thumb_mode == 'max') {
            $gd = new Gd($file_path);
            // 如果原图的宽度小于指定缩放的宽度，则宽度不参与缩放
            if (empty($new_width) || $gd->width < $new_width) {
                $new_width = null;
            }
            // 如果原图的高度小于指定缩放的高度，则高度不参与缩放
            if (empty($new_height) || $gd->height < $new_height) {
                $new_height = null;
            }
            $retu1 = $gd->scale($new_width, $new_height);
            $retu2 = $gd->saveAs($thumb_path);
        } elseif ($thumb_mode == 'merge') {
            // 融图的方案
            $gd = Gd::create($new_width, $new_height, MERGE_BG);
            $gd2 = new Gd($file_path);
            $gd2->scale($new_width, $new_height);
            $gd->merge_auto($gd2);
            $gd->saveAs($thumb_path);
        } elseif ($thumb_mode == 'cut') {
            // 切图的方案，按照指定的宽高比进行缩放到指定的比例，再切去多余的图
            $gd = new Gd($file_path);
            $gd->scale_fill($new_width, $new_height);
            $gd->saveAs($thumb_path);
        }
    }

    return true;
}

/**
 * 取得某资源的信息
 * @param string $res_name
 * @param int $res_id
 * @return array
 */
function get_res_info($res_name, $filter, $is_strict = 0)
{
    if (empty($res_name) || empty($filter)) {
        return array();
    }

    if (!is_array($filter)) {
        $filter = filter_string($filter);
    }
    if (is_numeric($filter)) {
        $filter = ['id' => $filter];
    }
    $res_info = _uri(filter_string($res_name), $filter);
    if (empty($res_info) || ($is_strict == 1 && $res_info['status'] != 1)) {
        return array();
    }

    return $res_info;
}

/**
 * 通过经纬度获取所在地
 * @param string $latitude
 * @param string $longitude
 * @return string
 */
function geocoder($latitude, $longitude)
{
    $city_url = 'http://api.map.baidu.com/geocoder/v2/?ak=44a48086aad408c7f189c58ea51e8abe&location={LATILONGI}&output=json&pois=0';
    $city_url = str_replace('{LATILONGI}', $latitude.','.$longitude, $city_url);

    $city_data = h_curl($city_url, null, 1);
    if (isset($city_data['result']['formatted_address'])) {
        return $city_data['result']['formatted_address'];
    }

    return '';
}


function get_act_content($link, $keyword, $open_id, $token)
{
    if(empty($link)){
        return '';
    }

//    $options = session('mp_options');
//    $token = $options['token'];
//    $openid = session('openid');
    $tmpArr = array('keyword'=>$keyword, 'tm'=>time(), 'openid'=>$open_id);
    $tmpArr['sign'] = get_token($tmpArr, $token);
    $param = http_build_query($tmpArr, '', '&');

    return h_curl($link.'?'.$param);
}
function get_token($paramArr, $signKey, $dot = '&')
{
    ksort($paramArr);
    $str = "";
    foreach($paramArr as $key=>$v){
        $str .= empty($str) ? $key . '=' . $v : $dot . $key . '=' . $v;
    }
    $sign = md5($str.$signKey);
    return $sign;
}